import json
import sys

import facade
import requests
from xjlibrary.our_file_dir import BaseDir, ImageFile

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")

TopPath = BaseDir.get_upper_dir(curPath, -2)
coverPath = BaseDir.get_new_path(TopPath, "download", "sipe", "download", "cover")
BaseDir.create_dir(coverPath)


class DownCOver(object):
    def __init__(self):
        self.mysqlutils = facade.MysqlUtiles(configfile,
                                             "db",
                                             logger=facade.get_streamlogger())

    def select(self):
        sn = requests.Session()
        url = "https://www.spiedigitallibrary.org/"
        headers = {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "zh-CN,zh;q=0.9",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"
        }
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      sn=sn,
                                                      headers=headers,
                                                      verify=False,
                                                      allow_redirects=True,
                                                      timeout=60)
        if BoolResult:
            print("访问首页成功")
        else:
            sys.exit(-1)

        sql = "select coverurl,`json` from books where coverstat=0"
        rows = self.mysqlutils.SelectFromDB(sql)
        for row in rows:
            url = row[0]
            url = "https://www.spiedigitallibrary.org" + url

            BoolResult, errString, r = facade.BaseRequest(url,
                                                          sn=sn,
                                                          headers=headers,
                                                          endstring="",
                                                          allow_redirects=True,
                                                          verify=False,
                                                          timeout=60)
            if BoolResult:
                dicts = json.loads(row[1])
                doi = dicts["DOI"]
                name = doi.replace("/", "_").lower()+".jpg"
                ImageFile.img_to_format_jpg(r.content, BaseDir.get_new_path(coverPath, name))
                sql = "update books set coverstat=1 where coverurl='{}'".format(row[0])
                self.mysqlutils.ExeSqlToDB(sql)


if __name__ == "__main__":
    down = DownCOver()
    down.select()
